class Solution {
public:
    int calculate(string s) {
        stack<int>stk;
        int num = 0;
        char sign='+';
        bool first = false;
        for (int i = 0; i < s.length(); i++) {
            if (s[i] == ' ') { continue; }
            if (isdigit(s[i])) {
                num = num * 10 + (s[i] - '0');
            }
            if (!isdigit(s[i])) {
                if (first) {
                    if (sign == '+') {
                        stk.push(num);
                    }
                    else if (sign == '-') {
                        stk.push(-num);
                    }
                    else if (sign == '*') {
                        num = num * stk.top();
                        stk.pop();
                        stk.push(num);
                    }
                    else {
                        num = stk.top() / num;
                        stk.pop();
                        stk.push(num);
                    }
                    sign = s[i];
                    num = 0;
                }
                else {
                    stk.push(num);
                    num = 0;
                    sign = s[i];
                    first = true;
                }
            }
        }
        if (sign == '+') {
            stk.push(num);
        }
        else if (sign == '-') {
            stk.push(-num);
        }
        else if (sign == '*') {
            num = num * stk.top();
            stk.pop();
            stk.push(num);
        }
        else if (sign == '/') {
            num = stk.top() / num;
            stk.pop();
            stk.push(num);
        }
        int answer = 0;
        while (!stk.empty()) {
            answer += stk.top();
            stk.pop();
        }
        return answer;
    }
};